//
//  SellViewController.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/8/15.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved. 销售的业务模块
//

#import "SellViewController.h"
#import "BLHeader.h"
#import "BusinessTableViewCell.h"
#import "Partner.h"
#import "PartnerDetailViewController.h"
#import "NSString+SortNameUtils.h"
#import "ScanAddPartnerViewController.h"
#import "SearchPartnerTableViewController.h"
#import "AddPartnerViewController.h"
#import "CommitAddPartnerViewController.h"
#import "SearchNet.h"
#import <MBProgressHUD.h>
#import <MJRefresh.h>
#import "VervifyPhone.h"
#import "FirstWeChatLoginView.h"


@interface SellViewController () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *partners;
@property (nonatomic, strong) NSArray *characters;
@property (nonatomic, strong) NSArray *grouplist;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) SearchPartnerTableViewController *searchVC;
@property (nonatomic, strong) UIAlertController *alert;

@end

@implementation SellViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    // 扫一扫 按钮
//    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(scanEvent)];
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"扫一扫" style:UIBarButtonItemStylePlain target:self action:@selector(scanEvent)];
     [right setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:kAppThemeColor ,NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = right;
    if([[[NSUserDefaults standardUserDefaults] objectForKey:USERCLASS] integerValue] == 1) {
        self.title = @"销售列表";
    }else {
        self.title = @"店主列表";
    }
    [NSString groupAndGetSectionTitles:self.partners objName:^NSString *(id obj) {
        Partner *p = obj;
        return p.name;
    } complement:^(NSArray<NSString *> *sectionTitles, NSArray<NSArray *> *groupLists) {
        self.grouplist = groupLists;
        self.characters = sectionTitles;
    }];
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"BusinessTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:ReuseIdentify];
    MJRefreshHeader *refreshHead = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataFromServer)];
    self.tableView.mj_header = refreshHead;
    //NSString *tel = [[NSUserDefaults standardUserDefaults] objectForKey:USERTEL];
    //if(tel && [tel length] != 0) {
        [self.tableView.mj_header beginRefreshing];
   // }
    self.tableView.tableHeaderView = self.searchController.searchBar;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //[self checkTel];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationEvent:) name:ADDPARTNERNOTIFICATION object:nil];
}

- (void)dataFromServer {
   // MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
   // hud.mode = MBProgressHUDModeIndeterminate;
    [SearchNet saleOrStoreList:^(id result, NSError *error) {
        if (result) {
            self.partners = result;
            // 重新分组
            [NSString groupAndGetSectionTitles:self.partners objName:^NSString *(id obj) {
                Partner *p = obj;
                return p.name;
            } complement:^(NSArray<NSString *> *sectionTitles, NSArray<NSArray *> *groupLists) {
                self.grouplist = groupLists;
                self.characters = sectionTitles;
            }];
            [self.tableView reloadData];
        }else {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = [error localizedDescription];
            [hud hideAnimated:YES afterDelay:2];
        }
        [self.tableView.mj_header endRefreshing];
    }];
}

#pragma mark 搜索
- (UISearchController *) searchController {
    if (_searchController == nil) {
        _searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchVC];
        [self addChildViewController:self.searchVC];
        _searchController.searchResultsUpdater = self.searchVC;
        self.searchVC.searchController = _searchController;
        [_searchController.searchBar setPlaceholder:@"搜索"];
        [_searchController.searchBar setBarTintColor:DEFAULT_SEARCHBAR_COLOR];
        [_searchController.searchBar sizeToFit];
        [_searchController.searchBar setDelegate:self.searchVC];
        [_searchController.searchBar.layer setBorderWidth:0.5f];
        [_searchController.searchBar.layer setBorderColor:WBColor(220, 220, 220, 1.0).CGColor];
       // _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.hidesNavigationBarDuringPresentation = YES;
    }
    return _searchController;
}

- (SearchPartnerTableViewController *) searchVC {
    if (_searchVC == nil) {
        _searchVC = [[SearchPartnerTableViewController alloc] init];
    }
    return _searchVC;
}

#pragma mrak 扫一扫同意
- (void)scanEvent {
    ScanAddPartnerViewController *scan = [[ScanAddPartnerViewController alloc] init];
    [self.navigationController pushViewController:scan animated:YES];
}


#pragma mark tableview delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BusinessTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseIdentify];
    if(indexPath.section == 0){
        [cell setupCell:nil indexPath:indexPath];
        return cell;
    }
    NSArray *list = self.grouplist[indexPath.section - 1];
    [cell setupCell:list[indexPath.row] indexPath:indexPath];
    return cell;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0) {
        return 1;
    }
    NSArray *list = self.grouplist[section - 1];
    return list.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 64;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.characters;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.characters.count + 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if(section ==0) {
        return nil;
    }
    return self.characters[section - 1];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 0) {
        AddPartnerViewController *add = [[AddPartnerViewController alloc] init];
        [self.navigationController pushViewController:add animated:YES];
        return;
    }
    PartnerDetailViewController *controller = [[PartnerDetailViewController alloc] init];
    controller.partner = self.partners[indexPath.row];
    [self.navigationController pushViewController:controller animated:YES];
}


- (void)notificationEvent:(NSNotification *)notification {
    Partner *partner = notification.object;
    if(!self.partners) {
        self.partners = @[partner];
    }
    [self.tableView reloadData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ADDPARTNERNOTIFICATION object:nil];
}
@end
